package cmd

import (
	"context"
	"fmt"
	"gsc/types"
	"gsc/utils"
	"os"

	"github.com/hashicorp/go-getter/v2"
	"github.com/spf13/cobra"
)

var gzeroActios = []types.UpdateFileAction{
	types.CreateUpdateFileAction("etc/wxorderserver-api.yaml", []types.ActionItem{
		{
			ActionItemType: 1,
			Replace:        "wx_order_server-api",
			Rewrite:        "${projectname}-api",
		},
		{
			ActionItemType: 1,
			Replace:        "wxorderserver",
			Rewrite:        "${projectname}",
		},
	}, "etc/${projectname}-api.yaml"),
	types.CreateUpdateFileAction("wx_order_server.api", []types.ActionItem{
		{
			ActionItemType: 1,
			Replace:        "wx_order_server-api",
			Rewrite:        "${projectname}-api",
		},
	}, "${projectname}-api.api"),
	types.CreateUpdateFileAction("wxorderserver.go", []types.ActionItem{
		{
			ActionItemType: 1,
			Replace:        "wxorderserver-api.yaml",
			Rewrite:        "${projectname}-api.yaml",
		},
	}, "${projectname}.go"),
	types.CreateUpdateFileAction("go.mod", []types.ActionItem{
		{
			ActionItemType: 1,
			Replace:        "module wx_order_server",
			Rewrite:        "module ${projectname}",
		},
	}, "go.mod"),
	types.CreateUpdateFileAction("README.md", []types.ActionItem{
		{
			ActionItemType: 1,
			Replace:        "wx_order_server.api",
			Rewrite:        "${projectname}-api.api",
		},
		{
			ActionItemType: 1,
			Replace:        "wxorderserver",
			Rewrite:        "${projectname}",
		},
	}, "README.md"),
	types.CreateUpdateFileAction("*.go", []types.ActionItem{
		{
			ActionItemType: 1,
			Replace:        "wx_order_server",
			Rewrite:        "${projectname}",
		},
	}, ""),
}

// creategzeroCmd represents the creategzero command
var creategzeroCmd = &cobra.Command{
	Use:   "cgzero",
	Short: "create gozero web template",
	Long:  `create gozero web template`,
	Run: func(cmd *cobra.Command, args []string) {
		if len(args) == 0 {
			fmt.Println("Please provide a name for the project")
			return
		}

		projectName := args[0]
		projectNamePath := "./" + projectName

		e := os.RemoveAll(projectNamePath)
		if e != nil {
			fmt.Println("删除项目目录失败")
			return
		}

		// temp 目录下创建项目
		// 1. 创建项目目录
		e = os.MkdirAll(projectNamePath, os.ModePerm)
		if e != nil {
			fmt.Println("创建项目目录失败")
			return
		}

		client := getter.Client{}

		client.Get(context.Background(), &getter.Request{
			Src: "git::https://gitee.com/shusc24/shusc-go-zero-template.git",
			Dst: "./" + projectName,
		})

		utils.WalkConfigTo(gzeroActios, projectName, ".")
		// 删除 .git 文件夹
		if e = os.RemoveAll(projectNamePath + "/.git"); e != nil {
			fmt.Println("Failed to remove .git directory")
			return
		}
	},
}

func init() {
	rootCmd.AddCommand(creategzeroCmd)
}
